package com.authine.cloudpivot.ext.controller;

import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.engine.api.model.bizmodel.BizPropertyModel;
import com.authine.cloudpivot.engine.api.model.bizmodel.BizSchemaModel;
import com.authine.cloudpivot.engine.api.model.organization.DepartmentModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.permission.AppPackagePermissionModel;
import com.authine.cloudpivot.engine.api.model.permission.PermissionGroupModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectQueryModel;
import com.authine.cloudpivot.engine.api.model.system.AdminModel;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.engine.domain.runtime.BizObject;
import com.authine.cloudpivot.engine.enums.type.AdminType;
import com.authine.cloudpivot.engine.enums.type.BizPropertyType;
import com.authine.cloudpivot.engine.enums.type.DefaultPropertyType;
import com.authine.cloudpivot.engine.enums.type.OperatorType;
import com.authine.cloudpivot.engine.service.system.SequenceSettingService;
import com.authine.cloudpivot.ext.domain.constant.CommonConstants;
import com.authine.cloudpivot.web.api.controller.base.BaseQueryRuntimeController;
import com.authine.cloudpivot.web.api.view.PageVO;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import com.authine.cloudpivot.web.api.view.runtime.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author：lpz
 * @CreateTime：2023-01-16 16:01
 * @Description: 二开高级查询接口, 修改默认模糊查询为精准查询
 */
@RestController
@RequestMapping("/api/advancedquery")
@Slf4j
public class AdvancedQueryController extends BaseQueryRuntimeController {

    @Autowired
    private SequenceSettingService sequenceSettingService;

    @ApiOperation(value = "高级查询", notes = "高级查询")
    @PostMapping("/list_reverse_sheet")
    public ResponseResult<PageVO<BizObjectModel>> listReverseSheet(@RequestBody QueryDataVO queryData) {
        validateNotEmpty(queryData.getSchemaCode(), "模型编码不能为空");
        BizSchemaModel bizSchema = getAppManagementFacade().getBizSchemaBySchemaCode(queryData.getSchemaCode());
        parseFilterVo(queryData, bizSchema);
        Object condition;
        if (queryData.getFilters() == null) {
            condition = null;
        } else {
            List<FilterVO> filters = queryData.getFilters();
            for (FilterVO filter : filters) {
                BizPropertyType propertyType = filter.getPropertyType();
                if (BizPropertyType.SHORT_TEXT.equals(propertyType)){
                    //如果是等于，设置为null走自定义的精准查询
                    if (OperatorType.EQ.equals(filter.getOperatorType())){
                        filter.setOperatorType(null);
                        filter.setPropertyValue(filter.getPropertyValue()+";list_reverse_sheet");
                    }
                }
            }
            condition = JSON.toJSONString(queryData.getFilters());
        }

        if (log.isDebugEnabled()) {
            log.debug("用于查询的条件为：【{}】", condition);
        }
        Page<BizObjectModel> data = queryBizObject(getUserId(), queryData, false, true, false);
        return this.getOkResponseResult(new PageVO<>(data), "获取数据成功");
    }

    /**
     * @description: 处理数据类型
     * @author: lpz
     * @date: 2023/1/19 16:41
     * @param: [queryData, bizSchema]
     * @return: void
     **/
    private void parseFilterVo(QueryDataVO queryData, BizSchemaModel bizSchema) {
        if (CollectionUtils.isEmpty(bizSchema.getProperties()) || CollectionUtils.isEmpty(queryData.getFilters())) {
            return;
        }
        Map<String, List<BizPropertyModel>> listMap = bizSchema.getProperties().stream().collect(Collectors.groupingBy(BizPropertyModel::getCode));
        for (FilterVO filterVO : queryData.getFilters()) {
            if (filterVO.getPropertyType() == null) {
                filterVO.setPropertyType(listMap.get(filterVO.getPropertyCode()).get(0).getPropertyType());
            }
        }
    }
}
